import React, { useRef, useState, useEffect } from 'react'

import Layout from '../common/layout'

import './index.less'
import { collectApi } from '../../apis/homeApi'

import echarts from 'echarts'


import PieNode from './PieNode'

let resizeTimer = null
function Home({ history, dispatch, }) {

  //  console.log(arguments)

  const barNode = useRef()

  const [barChart, setBarChart] = useState(null)


  useEffect(() => {
    // 返回一个echarts实例对象
    setBarChart(echarts.init(barNode.current))


    return function () {
      console.log('移除事件监听----------------------------')
      window.removeEventListener('resize', resizeChart)
    }
  }, [])

  function resizeChart() {
    if (!!barChart) {
      // 执行 echarts重绘，需要调用echarts的内置API resize
      if (!!resizeTimer) {
        console.log('-------------------------暂停 setTimeout,并且清除 setTimeout    ')
        clearTimeout(resizeTimer)
        resizeTimer = null
      }

      resizeTimer = setTimeout(() => {
        barChart.resize()
        resizeTimer = null
        console.log('------------------------绘制完成   ')
      }, 800)
    }

  }

  useEffect(async () => {

    if (!barChart) return
    window.addEventListener('resize', resizeChart)

    //  轮询业务的实现
    barLoop()

    //  给echarts图形设置鼠标点击事件 echartsInstance.on
    barChart.on('click', function () {
      console.log(arguments)
    })

  }, [barChart])

  async function barLoop() {

    let result = await collectApi()

    if (result.code === 200) renderBarChart(result.data || [])

    //1、短轮询实现，不设置时间
    /*   setTimeout(()=>{
          barLoop()
      })
      */

    // 长轮询的实现  需要给定时器设置时间
    setTimeout(() => {
      barLoop()
    }, 10000)

    function renderBarChart(list) {
      let series = []
      let label = ['总应收', '已收', '未收', '贷款收']
      let xAxisLabel = []
      let datas = [[], [], [], []]
      let colors = [['#d94e42', '#dc5246'], ['#ffcd40', '#4c8bf4'], ['#00da9c', '#007a55'], ['#75e44e', '#406aef']]

      list.forEach(element => {
        xAxisLabel.push(element.date)
        datas[0].push(element.total)
        datas[1].push(element.received)
        datas[2].push(element.receiving)
        datas[3].push(element.total)
      });

      series = label.map((name, i) => {
        return {
          name,
          type: 'bar',
          data: datas[i],
          barWidth: 10, //柱子宽度
          barGap: 0.1, //柱子之间间距
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: colors[i][0],
                offset: 1,
                color: colors[i][1]
              }]),
              opacity: 1,
            }
          }
        }
      })

      let option = {

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: label,
          align: 'right',
          right: 10,

          itemWidth: 10,
          itemHeight: 10,
          itemGap: 35
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: xAxisLabel,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#063374",
              width: 1,
              type: "solid"
            }
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#00c7ff",

            },
            //坐标轴间隔 
            interval: 0,
            //刻度标签旋转的角度 
            rotate: 20

          },
        }],
        yAxis: [{
          type: 'value',
          axisLabel: {
            formatter: '{value} 元'
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#00c7ff",
              width: 2,
              type: "solid"
            },
          },
          splitLine: {
            lineStyle: {
              color: "#063374",
            }
          }
        }],
        series: series
      };
      // setOption方法要接收一个参数 -- 图形配置对象
      barChart.setOption(option)
    }
  }



  return (
    <div className="home-container">
      <div className="left">
        <PieNode />
      </div>
      <div className="right">
        <div ref={barNode} className="chart-box"></div>
      </div>
      <div className="left"></div>
      <div className="right"></div>
    </div>
  )
}
export default Layout(Home)   //  使其为一个功能增强组件